package com.github.dynamic.datasource.annotation;

import com.github.dynamic.datasource.configuration.CustomDynamicDataSource;
import com.github.dynamic.datasource.constant.DataSourceNameConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;

import java.lang.reflect.Method;

@Slf4j
@Aspect
public class DataSourceAspectProcessor implements AutoCloseable, Ordered {

    @Pointcut("@annotation(DSRouter)")
    public void pointcut(){

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DSRouter router = method.getAnnotation(DSRouter.class);

        if (router == null) {
            CustomDynamicDataSource.setDataSource(DataSourceNameConstant.MASTER);
            log.debug("set datasource is " + DataSourceNameConstant.MASTER);

        } else {
            CustomDynamicDataSource.setDataSource(router.value());
            log.debug("set datasource is " + router.value());
        }

        try {
            return point.proceed();
        } finally {
            close();
            log.debug("clean datasource");
        }

    }

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void close() throws Exception {
        CustomDynamicDataSource.clearDataSource();
    }
}
